package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.model.DeliveryAddress;
import cn.edu.tju.elm.service.AddressService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api")
@Tag(name = "管理地址", description = "对配送地址的增删改查")
public class AddressController {
    
    @Autowired
    private AddressService addressService;

    @Autowired
    private UserService userService;

    @PostMapping("/addresses")
    @Operation(summary = "添加配送地址", description = "创建新的配送地址")
    public HttpResult<DeliveryAddress> addAddress(@RequestBody DeliveryAddress address) {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 设置地址所属用户
            address.setCustomer(currentUser);
            
            // 设置创建和更新信息
            LocalDateTime now = LocalDateTime.now();
            address.setCreator(currentUser.getId());
            address.setCreateTime(now);
            address.setUpdater(currentUser.getId());
            address.setUpdateTime(now);
            address.setDeleted(false);
            
            // 设置默认性别为男(1)，如果未提供性别
            if (address.getContactSex() == null) {
                address.setContactSex(1); // 1代表男
            }
            
            // 验证性别
            if (address.getContactSex() != 1 && address.getContactSex() != 2) {
                return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "性别必须为1(男)或2(女)");
            }
            
            // 通过服务层处理地址添加逻辑
            DeliveryAddress savedAddress = addressService.addAddress(address, currentUser);
            return HttpResult.success(savedAddress);
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "添加地址失败: " + e.getMessage());
        }
    }

    @GetMapping("/addresses")
    @Operation(summary = "获取用户地址列表", description = "获取当前用户的所有配送地址")
    public HttpResult<List<DeliveryAddress>> getUserAddresses() {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 获取用户的所有地址
            List<DeliveryAddress> addresses = addressService.findByCustomer(currentUser);
            return HttpResult.success(addresses);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "获取地址列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/addresses/{id}")
    @Operation(summary = "获取指定地址", description = "根据ID获取地址详情")
    public HttpResult<DeliveryAddress> getAddressById(@PathVariable Long id) {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 获取地址并验证是否属于当前用户
            Optional<DeliveryAddress> addressOpt = addressService.findById(id);
            if (addressOpt.isPresent()) {
            	DeliveryAddress address = addressOpt.get();
                if (address.getCustomer().getId().equals(currentUser.getId())) {
                    return HttpResult.success(address);
                } else {
                    return HttpResult.failure(ResultCodeEnum.FORBIDDEN, "无权访问此地址");
                }
            } else {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "地址不存在");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "获取地址失败: " + e.getMessage());
        }
    }

    @PutMapping("/addresses/{id}")
    @Operation(summary = "更新地址", description = "更新指定ID的地址信息")
    public HttpResult<DeliveryAddress> updateAddress(@PathVariable Long id, @RequestBody DeliveryAddress addressDetails) {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层更新地址
            DeliveryAddress updatedAddress = addressService.updateAddress(id, addressDetails, currentUser);
            return HttpResult.success(updatedAddress);
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, e.getMessage());
        } catch (RuntimeException e) {
            if (e.getMessage().contains("无权") || e.getMessage().contains("不存在")) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
            }
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "更新地址失败: " + e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "更新地址失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/addresses/{id}")
    @Operation(summary = "删除地址", description = "删除指定ID的地址")
    public HttpResult<String> deleteAddress(@PathVariable Long id) {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 通过服务层删除地址
            addressService.deleteAddress(id, currentUser);
            return HttpResult.success("地址删除成功");
        } catch (RuntimeException e) {
            if (e.getMessage().contains("无权") || e.getMessage().contains("不存在")) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
            }
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "删除地址失败: " + e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "删除地址失败: " + e.getMessage());
        }
    }

    @PutMapping("/addresses/{id}/default")
    @Operation(summary = "设置默认地址", description = "将指定ID的地址设置为默认地址")
    public HttpResult<DeliveryAddress> setDefaultAddress(@PathVariable Long id) {
        try {
            // 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));
            
            // 设置默认地址
            DeliveryAddress defaultAddress = addressService.setDefaultAddress(id, currentUser);
            return HttpResult.success(defaultAddress);
        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "设置默认地址失败: " + e.getMessage());
        }
    }
}
